<template>
  <el-card class="mt-10">
    <el-form>
      <el-form-item label="属性名">
        <el-input
          class="form__input"
          placeholder="请输入属性名"
          v-model="attrFormData.attrName"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="addAttrValue"
          :disabled="!attrFormData.attrName"
        >
          添加属性值
        </el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
      <el-form-item>
        <el-table class="mb-20" :data="attrFormData.attrValueList">
          <el-table-column
            width="80"
            label="序号"
            type="index"
            align="center"
          />
          <el-table-column prop="date" label="属性值名称" width="566">
            <template v-slot="{ row, $index }">
              <el-input
                size="small"
                ref="inputRef"
                v-if="row.isShowEdit"
                v-model="row.valueName"
                @blur="switch2Text(row, $index)"
                @keyup.enter="switch2Text(row, $index)"
              />
              <div v-else class="attr__div" @click="switch2Edit(row)">
                {{ row.valueName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row, $index }">
              <el-popconfirm
                @confirm="deleteAttrValue($index)"
                :title="`您确定要删除${row.valueName}属性值吗?`"
              >
                <template #reference>
                  <el-button
                    size="small"
                    title="删除"
                    type="danger"
                    :icon="Delete"
                  />
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit" :disabled="disabled">
          保存
        </el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "AddOrUpdateAttr",
};
</script>

<script lang="ts" setup>
import { reactive, ref, nextTick, computed } from "vue";
import { Delete } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { addOrUpdateAttrApi } from "@/api/product/attr";
import { useCategoryStore } from "@/stores/category";
import { useAttrInfo } from "@/stores/attr";
import type {
  AttrInfoItem,
  AttrValueItem,
} from "@/api/product/model/attrModel";
// 获取输入框的ref对象
const inputRef = ref();
// 定义表单数据
const attrInfo = useAttrInfo();
const attrFormData = reactive<AttrInfoItem>({
  attrName: attrInfo.attrInfo.attrName,
  attrValueList: attrInfo.attrInfo.attrValueList,
});
// 判断保存按钮是否禁用
const disabled = computed(() => {
  return (
    !attrFormData.attrName ||
    !attrFormData.attrValueList.some((attrValue) => {
      return attrValue.valueName;
    })
  );
});
// 添加属性值
const addAttrValue = async () => {
  attrFormData.attrValueList.push({
    isShowEdit: true,
    valueName: "",
  });
  // 由于页面渲染是异步的，而inputRef.value.focus();执行时同步的
  // 所以，会导致第一次拿不到inputRef.value而报错
  // 调用nextTick方法，加入异步队列
  await nextTick();
  inputRef.value.focus();
};
// 切换到显示模式
const switch2Text = (row: AttrValueItem, index: number) => {
  // 如果输入的值为空，则删除该条数据
  if (!row.valueName) {
    attrFormData.attrValueList.splice(index, 1);
    return;
  }
  const isRepeat = attrFormData.attrValueList.some((item) => {
    if (item === row) return false;
    if (item.valueName === row.valueName) return true;
    return false;
  });
  if (isRepeat) {
    ElMessage.warning("请不要输入重复的属性值");
    attrFormData.attrValueList.splice(index, 1);
    return;
  }
  // 修改标识
  row.isShowEdit = false;
};
// 切换到编辑模式
const switch2Edit = async (row: AttrValueItem) => {
  // 修改标识
  row.isShowEdit = false;
  // 并自动获得焦点
  await nextTick();
  inputRef.value.focus();
};
// 删除属性值
const deleteAttrValue = (index: number) => {
  attrFormData.attrValueList.splice(index, 1);
};
// 提交按钮
const categoryStore = useCategoryStore();
const submit = async () => {
  const data = {
    ...attrFormData,
    categoryId: categoryStore.category3Id as number,
    categoryLevel: 3,
  };
  const id = attrInfo.attrInfo.id;
  if (id) {
    data.id = id;
  }
  await addOrUpdateAttrApi(data);
  ElMessage.success(`${id ? "修改" : "添加"}成功`);
  cancel();
};

// 接收自定义事件
const emit = defineEmits(["updateIsShowAttrList"]);
// 取消按钮
const cancel = () => {
  emit("updateIsShowAttrList", false);
};
</script>

<style scoped>
.form__input {
  width: 200px;
}
</style>
